<template>
  <div id="login" class="login">
    <div class="login_top">
      <el-row class="top_inner" type="flex" justify="space-between">
        <el-col>
          <img src alt>
          <span>
            <router-link to="/">七多多</router-link>
            | {{Ttile}}
          </span>
        </el-col>
        <el-col>
          <span>还没有账号</span>
          <router-link to="./"><span>首页</span></router-link>
          <!-- <span class="register">注册</span> -->
        </el-col>
      </el-row>
    </div>
    <div class="login_mid">
      <div id="login_container"></div>
      <div class="mid_left">
        <img
          src="//gss0.bdstatic.com/8r1VfDn9KggZnd_b8IqT0jB-xx1xbK/static/user/img/login-logo_30a0915.png"
          alt
        >
      </div>
      <div class="mid_right">
        <div class="m_r_title">{{Ttile}}七多多</div>
        <div class="teleLogin newuser" v-if="isnewuser">新用户绑定手机号</div>
        <div class="teleLogin" v-else>
          <div
            v-for="(item,index) in logtype"
            :key="index"
            @click="handlogin(item.ind)"
            :class="gotype==item.ind?'acttype':''"
          >
            <img :src="item.imgurl" alt>
            <span>{{item.text}}{{Ttile}}</span>
          </div>
        </div>
        <div class="form">
          <div class="oldUserLogin">
            <div class="form_input">
              <div class="inp_icon">
                <img src="../../../static/images/man.jpg" alt>
              </div>
              <input
                type="number"
                placeholder="手机/用户名"
                v-model="phone"
                minlength="1"
                maxlength="11"
              >
            </div>
            <div class="form_input">
              <div class="inp_icon">
                <img src="../../../static/images/lock.jpg" alt>
              </div>
              <input type="password" placeholder="验证码" v-model="password">
              <button @click="handverfiy">
                {{verfiy}}
                <span v-show="typeof(verfiy)=='number'">称后再次发送</span>
              </button>
            </div>
          </div>
          <el-button type="info" disabled v-if="isnewuser">登录</el-button>
          <el-button type="primary" v-else @click="isVerify">登录</el-button>
        </div>
      </div>
    </div>
    <div class="login_bot"></div>
  </div>
</template>

<script>
// this.$GLOBAL.API+"  <==> "/api/ 打包所有替换
import qs from "qs";
import { mapState, mapMutations } from "vuex";
import { Message } from "element-ui";
var oFrm = null;
export default {
  name: "Login",
  data() {
    return {
      gotype: 2,
      Ttile: "登陆",
      verfiy: "获取验证码",
      logtype: [
        {
          ind: 2,
          text: "短信快捷",
          imgurl: "../../../static/images/iphone.png"
        },
        {
          ind: 1,
          text: "微信",
          imgurl: "../../../static/images/wxlogo.png"
        }
      ],
      phone: "",
      password: "",
      timeFlag: true,
      codeObj: {},
      wxInfo: {},
      veridyBtn: "发送动态密码",
      timer: null,
      isChecked: false,
      timer2: null,
      isnewuser: false
    };
  },
  watch: {},
  computed: {
    ...mapState(["userInfo", "userId", "token"])
  },
  mounted() {
    let url = window.location.href;
    if (url.indexOf("?") > 0) {
      let arr = url.split("?");
      let str = arr[1],
        object = {};
      if (arr[1].indexOf("code") != -1) {
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          object[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
        this.codeObj = object;
        if (object.code) {
          // console.log("code:", object.code);
          this.getwxinfo(object.code);
        }
      }
    }
  },
  methods: {
    ...mapMutations(["setUserInfo", "setUserId", "setToken"]),
    //点击微信登录
    handlogin(val) {
      this.gotype = val;
      if (val == 1) {
        if (!this.wxcode) {
          window.location.href =
            "https://open.weixin.qq.com/connect/qrconnect?appid=wxbb3b60fdb2724986&redirect_uri=https%3a%2f%2fxiang7.net%2fhome%2f%23%2flogin&response_type=code&scope=snsapi_login&state=34c73911b09c93d66316e2965199b932#wechat_redirect";
        }
      }
    },
    //点击获取验证码
    handverfiy() {
      let _this = this;
      if (!this.isPhone(this.phone)) {
        this.toast("请输入正确的手机号码");
      } else if (!this.timeFlag) {
        _this.toast("验证码发送中，请稍候！");
      } else {
        this.timeFlag = false;
        this.$axios
          .post(
           "/api/webApprove/auth/sendForShopAppRegister?shopMobile=" +
              this.phone
          )
          .then(res => {
            let data = res.data;
            if (data.code == 0) {
              let seconds = "",
                countdown = 60;
              _this.verifyCode = data.data.verifyId;
              console.log("verifyCode:", _this.verifyCode);
              _this.timer = setInterval(() => {
                countdown--;
                if (countdown <= 0) {
                  _this.verfiy = "获取验证码";
                  clearInterval(_this.timer);
                  _this.timeFlag = true;
                } else {
                  _this.verfiy = countdown + "秒后重新发送";
                }
              }, 1000);
            } else {
              _this.timeFlag = false;
              _this.toast("系统繁忙，请稍后再试");
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    //判断输入验证码是否正确
    isVerify() {
      let _parms = {},
        value = "",
        _this = this;
      if (!this.isPhone(this.phone)) {
        this.toast("请输入正确的手机号码");
        return false;
      } else if (!this.password) {
        this.toast("请输入短信验证码");
        return false;
      }
      if (this.verifyCode && this.verifyCode != this.password) {
        this.toast("验证码输入错误");
        return false;
      }
      _parms = {
        shopMobile: this.phone,
        smsContent: this.password
      };
      for (var key in _parms) {
        value += key + "=" + _parms[key] + "&";
      }
      value = value.substring(0, value.length - 1);
      this.$axios
        .get("/api/webApprove/auth/isVerifyForShopApp?" + value)
        .then(res => {
          if (res.data.code == 0 && res.data.data == 0) {
            _this.isOldUser();
          } else {
            _this.toast("输入信息有误");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //是否是老用户
    isOldUser() {
      let _this = this;
      this.$axios
        .get("/api/webApprove/auth/findUserByMobile?mobile=" + this.phone)
        .then(res => {
          if (res.data.code == 0) {
            if (res.data.data) {
              _this.setUserInfo(res.data.data);
              _this.setUserId(res.data.data.id);
              _this.login();
            } else {
              _this.addUser();
            }
          } else {
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //增加新用户
    addUser() {
      let _parms = {},
        value = "",
        _wxInfo = Object.keys(this.wxInfo),
        _this = this;
      _parms = {
        userName: this.phone,
        mobile: this.phone
      };
      if (_wxInfo.length > 0) {
        _parms = Object.assign(_parms, _wxInfo); //合并对象
      }
      this.$axios
        .post("/api/webApprove/auth/addShopAppUser",qs.stringify(_parms))
        .then(res => {
          if (res.data.code == 0) {
            if (res.data.data) {
              _this.setUserInfo(res.data.data);
              _this.setUserId(res.data.data.id);
              _this.login();
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //用户登录
    login() {
      let _this = this;
      this.$axios
        .post("/api/webApprove/auth/login?userName=" + this.phone)
        .then(res => {
          let token = "Bearer " + res.data.data;
          sessionStorage.setItem("TOKEN", token);
          if (res.data.code == 0 && token) {
            _this.setToken(token);
            if (_this.isChecked) {
              expiryTime = new Date().getTime() + 604800000; //7天后过期清除
            }
            if (sessionStorage.getItem("oldhref")) {
              const _url=sessionStorage.getItem("oldhref");
              sessionStorage.removeItem("oldhref");
              window.location.href =_url;
            } else {
              this.$router.push({ name: "index" });
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //通知
    toast(str) {
      this.$message({
        message: str,
        type: "warning",
        center: true
      });
    },
    //校验手机号是否正确
    isPhone() {
      let flag = false;
      if (this.phone) {
        let RegExp = /^(1[3456789]\d{9})$/;
        if (RegExp.test(this.phone)) {
          flag = true;
        }
      }
      return flag;
    },
    register() {
      this.$router.push({ name: "Register" });
    },
    //微信扫码后，通过code获取用户信息
    getwxinfo(code) {
      console.log("code:", code);
      const _this = this;
      this.$axios
        .get("/api/webApprove/auth/wXUserInfo?code=" + code)
        .then(res => {
          console.log("wxuserinfo:", res);
          if (res.data.code == 0) {
            if (res.data.data.mobile) {
              _this.phone = res.data.data.mobile;
              _this.isOldUser();
            } else {
              _this.wxInfo = res.data.data;
              _this.isnewuser = false;
            }
          }
        })
        .catch(err => {
          console.log("err:", err);
        });
    }
  },
  created() {
    // let _url = window.location.href;
    if (this.$route.query.flag == "zc") {
      this.Ttile = "注册";
    } else {
      this.Ttile = "登陆";
    }
  }
};
</script>

<style lang="less">
body,
html {
  margin: 0px;
  padding: 0px;
}

.login {
  font-size: 12px;
  min-width: 1340px;
  #codeIMG {
    width: 400px;
    height: 400px;
  }
  .login_top {
    height: 80px;
    border-bottom: 1px solid #dbdbdb;
    .top_inner {
      height: 100%;
      line-height: 80px;
      text-align: center;
      .register {
        display: inline-block;
        width: 64px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        border: 1px solid #ddd;
        border-radius: 3px;
        color: #666;
        cursor: pointer;
      }
    }
  }

  .login_mid {
    display: flex;
    justify-content: center;
    text-align: left;
    .mid_left {
      img {
        width: 600px;
        height: 300px;
      }
    }
    .mid_right {
      width: 300px;
      margin-top: 49px;
      padding: 20px 14px 40px 14px;
      width: 279px;
      border: 1px solid #eee;
      background: #fff;
      border-radius: 4px;

      .m_r_title {
        font-size: 17px;
        font-weight: 700;
        color: #666;
      }

      .teleLogin {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        color: #666;
        cursor: pointer;
        margin: 10px 0;
        & > div {
          width: 50%;
          text-align: center;
        }
        .acttype {
          background: pink;
        }
        img {
          width: 20px;
          height: 22px;
          margin-right: 2px;
        }
      }
      .newuser {
        justify-content: center;
      }
      .form {
        .form_input {
          background-color: #fff;
          margin-bottom: 15px;
          position: relative;
          input {
            margin: 0 !important;
            width: 100%;
            height: 40px;
            box-sizing: border-box;
            border: 2px solid #f0f0f0;
            border-radius: 4px;
            padding: 0 0 0 34px;
          }
          input[type="password"] {
            width: 50%;
          }
          .inp_icon {
            height: 40px;
            width: 34px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: absolute;
            left: 0;
            top: 0;
            img {
              width: 16px;
              height: 16px;
            }
          }
          & > button {
            margin: 0;
            padding: 10px 20px;
            margin-left: 10px;
            cursor: pointer;
          }
        }
        .isAutoLogin {
          display: flex;
          justify-content: space-between;
          align-items: stretch;
          margin-top: 15px;
          .AutoCheckBox {
            display: flex;
            align-items: stretch;
          }
        }
        .authCode {
          display: flex;
          justify-content: space-between;
          line-height: 38px;
          input {
            width: 55%;
            height: 38px;
            padding-left: 20px;
            border: 1px solid #f0f0f0;
            border-radius: 2px;
            box-sizing: border-box;
            color: #999;
          }
          .sendCode {
            width: 40%;
            height: 38px;
            background-color: #f7f7f7;
            border: 1px solid #dadada;
            border-radius: 2px;
            box-sizing: border-box;
            color: #666;
            cursor: pointer;
            text-align: center;
            &:hover {
              background-color: rgb(236, 234, 234);
            }
          }
        }
        button {
          margin-left: 35%;
          margin-top: 30px;
        }
      }
    }
  }
}
</style>


